import json
import os

import pytest

from api.api import user_login
from utils.msyql_util import db
from utils.read import base_data
from utils.redis_util import redis_util


def get_data():
    return base_data.read_yaml()


def get_code(mobile):
    sql = "select code from users_verifycode where mobile = '%s' order by id desc limit 1;" % mobile
    code = db.query(sql)['code']
    return code


def delete_code(mobile):
    sql = "delete from users_verifycode where mobile = '%s'" % mobile
    db.execute_db(sql)


def delete_user(mobile):
    sql = "delete from users_userprofile where mobile = '%s'" % mobile
    db.execute_db(sql)


# 获取用户token信息
@pytest.fixture
def get_user_token():
    # 减少登录接口调用次数，
    # 使用redis存储 token、mobile 信息
    if not (redis_util.exists('token') or redis_util.exists('mobile')):
        data = get_data()['get_user_token']
        mobile = data['mobile']
        password = data['password']
        res = user_login(mobile, password)
        # 将token、mobile信息存储到redis中，过期时间3600秒
        redis_util.set('token', res.body['token'], ex=3600)
        redis_util.set('mobile', str(mobile), ex=3600)
        redis_util.redis_client.get()
        return res.body['token'], mobile
    return redis_util.get('token').decode('utf-8'), redis_util.get('mobile').decode('utf-8')
